<template>
  <a-modal
    v-model="isModalVisible"
    :mask-closable="false"
    title="嵌合成数组"
    class="chimera-column"
    cancel-text="取消"
    ok-text="嵌合"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-row class="row">
      <a-col :span="4" class="label">
        待嵌合字段:
      </a-col>
      <a-col
        :span="16"
        style="line-height: 30px;"
        :class="{ 'has-error': hasError }"
      >
        {{ selectedColumnsName }}
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="label">
        新字段名:
      </a-col>
      <a-col :span="16" :class="{ 'has-error': hasError }">
        <a-input v-model="newCol" placeholder="请输入新字段名" /><br />
        <span v-show="hasError" class="error-message">请输入新字段名</span>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script lang="ts">
/**
 * 2021.7 嵌合成数组
 */
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { IColumn, IKeyValueStore } from '@/store/modules/dataview'
import { apiGetTableData } from '@/api/data-clean'
import { StatisticsAction } from '@/util/data-selection-actions'

@Component
export default class ChimeraIntoArray extends Vue {
  @Prop() column!: IColumn
  @Prop() editData!: any
  @Prop() taskId!: string
  @Prop({ default: false }) isEdit!: boolean
  @Prop({ default: '' }) parentTableName!: boolean
  @Prop({ default: [] }) selectedColumns!: IColumn[]

  private isModalVisible: boolean = true // model 框的显示
  private hasError: boolean = false // 报错
  private newCol: string = '' // 新列名
  private originCols: IColumn[] = []
  private originSelectedCols: IColumn[] = []

  private get columns() {
    return this.isEdit ? this.originSelectedCols : this.selectedColumns
  }

  // 选择嵌合的列拼接 字符串
  private get selectedColumnsName() {
    return this.columns.map((item) => item.name).join('、')
  }

  // 合并简介
  private get formatDescription() {
    const newCol = this.newCol.trim()
    return `嵌合成数组，嵌合名：${newCol}，来自：${this.selectedColumnsName}`
  }

  // public mounted() {
  //   this.newCol = this.columns.map((item) => item.name).join('_')
  // }

  @Watch('editData', { immediate: true, deep: true })
  private async onCurrentHistory(newValue: IKeyValueStore) {
    if (!newValue || !this.isEdit) {
      return
    }
    const history = newValue.data
    // 嵌合 action && 列名匹配
    if (
      history.actionType === StatisticsAction.chimeraIntoArray &&
      history.col === this.column.name
    ) {
      this.newCol = history.newCol
      await this.getOriginColumns() // 获取原始列名（上一次的修改表命）
      this.originSelectedCols = history.cols.map(
        (item: string) =>
          this.originCols.filter((column) => column.name === item)[0]
      )
      this.isModalVisible = true
    }
  }

  // 编辑状态下获取嵌合前的列数据
  private async getOriginColumns() {
    if (!this.isEdit) {
      return this.columns
    }
    const tableName = this.parentTableName // 编辑状态下是基于上一条记录的表名来进行筛选

    if (tableName) {
      // parentTableName存在
      const response = await apiGetTableData({
        data: {
          curPage: 1,
          name: '_record_id_', // 如果没有字段，那就固定传 _record_id_
          pageSize: 50,
          filter: [],
          table: tableName,
          taskId: this.taskId,
        },
      })
      const { result } = response.data
      this.originCols = result.head
    }
    return []
  }

  onOk() {
    if (this.newCol) {
      this.emitChimeraParams()
    }
  }

  onCancel() {
    this.$emit('on-filter-params-change', null)
    this.$emit('config-cancel')
    this.isModalVisible = false
  }

  /**
   * 抛出去清洗动作参数 嵌合对象
   */
  private emitChimeraParams() {
    const newCol = this.newCol.trim() // 新列var flag = false; //用来判断
    // TODO
    // let flag = false
    // const reg = /(^_([\da-z]_?)*$)|(^[a-z](_?[\da-z])*_?$)/
    // flag = reg.test(newCol)
    // 首位可以是字母以及下划线。首位之后可以是字母，数字以及下划线。下划线后不能接下划线
    if (!newCol) {
      this.$message.warning('请输入合法列名！')
      return
    }
    const data: any = {
      action: 'ARRAY_MERGE',
      cols: this.columns.map((item) => item.name),
      newCol,
      col: newCol, // 与列合并保持一致， 同时 DataColumns.vue 用到 data.col, 传参 newCol col
      columnName: newCol,
    }

    this.$emit('on-filter-params-change', {
      data: {
        ...data,
        description: this.formatDescription,
        actionType: StatisticsAction.chimeraIntoArray,
      },
    })
  }
}
</script>

<style lang="less" scoped>
.chimera-column {
  .row {
    margin-bottom: 14px;
  }

  .label {
    line-height: 30px;
    margin-right: 8px;
    text-align: right;
  }

  .select {
    margin-right: 12px;
    width: 120px;
  }

  .error-message {
    color: #f5222d;
    font-size: 12px;
    line-height: 1.5;
  }
}
</style>
